/*
 * Join a directory and a filename
 *
 * Copyright 2023 Odin Kroeger.
 *
 * This file is part of suCGI.
 *
 * suCGI is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * suCGI is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General
 * Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with suCGI. If not, see <https://www.gnu.org/licenses/>.
 */

#define _XOPEN_SOURCE 700

#include <sys/types.h>
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "path.h"
#include "types.h"

int
path_join(const size_t size, char *const path,
          const char *const dir, const char *const fname,
          const ErrorFn errh)
{
    assert(path != NULL || size == 0U);
    assert(dir != NULL);
    assert(*dir != '\0');
    assert(fname != NULL);
    assert(*fname != '\0');

    (void) memset(path, '\0', size);

    errno = 0;
    /* RATS: ignore; format is a literal */
    int len = snprintf(path, size, "%s/%s", dir, fname);
    if (len < 0) {
        if (errh != NULL) {
            errh(EXIT_FAILURE, "path_join");
        }

        return len;
    }

    if (size > 0U && (size_t) len >= size) {
        errno = ENAMETOOLONG;
        if (errh != NULL) {
            errh(EXIT_FAILURE, "path_join");
        }

        return -1;
    }

    return len;
}
